package com.lixh.sdk.base.promision.contract

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.core.app.ActivityCompat

class RequestWifiContract : ActivityResultContract<Unit, Boolean>() {
    var context: Context? = null

    override fun createIntent(context: Context, input: Unit): Intent {
        this.context = context
        //是否打开WIFI
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Intent(Settings.Panel.ACTION_WIFI).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
        } else {
            //需要定位权限才能扫描设备
            Intent(RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS).putExtra(
                RequestMultiplePermissions.EXTRA_PERMISSIONS, arrayOf(
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                )
            )
        }
    }


    private fun isEnabledWifi(context: Context) = lazy {
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        wifiManager.isWifiEnabled
    }.value

    private fun setEnabledWifi(context: Context) {
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        @Suppress("DEPRECATION")
        wifiManager.isWifiEnabled = true
    }

    override fun getSynchronousResult(
        context: Context, input: Unit
    ): SynchronousResult<Boolean>? {
        val isEnabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            isEnabledWifi(context)
        } else {
            setEnabledWifi(context)
            true
        }
        if (isEnabled && hasPermission()
        ) {
            return SynchronousResult(true)
        }
        return null
    }


    private fun hasPermission(): Boolean {
        return context?.let {
            arrayOf(
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
            ).none { permission ->
                ActivityCompat.checkSelfPermission(
                    it, permission
                ) == PackageManager.PERMISSION_GRANTED
            }
        } ?: false
    }

    override fun parseResult(resultCode: Int, intent: Intent?): Boolean = context?.let {
        val isEnabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            isEnabledWifi(it)
        } else {
            setEnabledWifi(it)
            true
        }
        isEnabled && hasPermission()
    } ?: false


}